import tkinter as tk
from tkinter import filedialog, messagebox, ttk, simpledialog
from PIL import Image, ImageTk, UnidentifiedImageError
import image_enhancement
import image_conversion
import utils  # 导入辅助函数
import image_filtering  # 导入图像滤波模块
import matplotlib.pyplot as plt  # 用于显示直方图
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import os  # 用于批量处理
from functools import partial  # 为了传递参数给command
import numpy as np

class ImageProcessorGUI:
    def __init__(self, master):
        self.master = master
        master.title("高级图像处理器")
        master.geometry("1000x700")  # 设置窗口大小

        self.original_image = None
        self.processed_image = None
        self.image_path = None  # 保存图像路径

        # 设置 Matplotlib 使用中文字体 (可选，如果需要显示中文)
        # plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 替换为你安装的字体
        # plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示为方块的问题

        # 创建直方图 Figure (只创建一次)
        self.histogram_figure = plt.Figure(figsize=(4, 3), dpi=100)
        self.histogram_ax = self.histogram_figure.add_subplot(111)

        # GUI 元素
        self.create_widgets()

    def create_widgets(self):
        # --- 菜单栏 ---
        menubar = tk.Menu(self.master)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="打开", command=self.select_image)
        filemenu.add_command(label="打开文件夹", command=self.select_folder)  # 批量处理
        filemenu.add_command(label="保存", command=self.save_image)
        filemenu.add_separator()
        filemenu.add_command(label="退出", command=self.master.quit)
        menubar.add_cascade(label="文件", menu=filemenu)

        editmenu = tk.Menu(menubar, tearoff=0)  # 编辑菜单
        editmenu.add_command(label="添加水印", command=self.add_watermark)
        menubar.add_cascade(label="编辑", menu=editmenu)

        self.master.config(menu=menubar)

        # --- 上方面板 (图像显示和RGB曲线图) ---
        self.top_frame = tk.Frame(self.master)
        self.top_frame.pack(pady=10)

        # 图像显示
        self.image_frame = tk.Frame(self.top_frame, width=600, height=400, bd=2, relief=tk.SUNKEN)
        self.image_frame.pack(side=tk.LEFT, padx=10)
        self.image_label = tk.Label(self.image_frame)
        self.image_label.pack(expand=True, fill=tk.BOTH)

        # RGB 曲线图显示
        self.histogram_frame = tk.Frame(self.top_frame, width=400, height=400, bd=2, relief=tk.SUNKEN)
        self.histogram_frame.pack(side=tk.LEFT, padx=10)
        self.histogram_label = tk.Label(self.histogram_frame)  # 用于显示提示信息
        self.histogram_label.pack()

        # 创建 TkAgg 画布 (只创建一次)
        self.canvas = FigureCanvasTkAgg(self.histogram_figure, master=self.histogram_frame)
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        # --- 下方面板 (控制) ---
        self.control_frame = tk.Frame(self.master)
        self.control_frame.pack(pady=5)

        # --- 增强功能选项卡 ---
        self.tabControl = ttk.Notebook(self.control_frame, width=950, height=200)  # 扩展宽度
        self.tabControl.pack(expand=True, fill="both")

        # 增强选项卡
        self.enhancement_tab = ttk.Frame(self.tabControl)
        self.tabControl.add(self.enhancement_tab, text="增强")
        self.create_enhancement_controls(self.enhancement_tab)

        # 转换选项卡
        self.conversion_tab = ttk.Frame(self.tabControl)
        self.tabControl.add(self.conversion_tab, text="转换")
        self.create_conversion_controls(self.conversion_tab)

        # 滤波选项卡
        self.filtering_tab = ttk.Frame(self.tabControl)
        self.tabControl.add(self.filtering_tab, text="滤波")
        self.create_filtering_controls(self.filtering_tab)

        # --- 底部按钮 ---
        self.bottom_frame = tk.Frame(self.master)
        self.bottom_frame.pack(pady=10)

        # 重置按钮
        self.reset_button = tk.Button(self.bottom_frame, text="重置", command=self.reset_image)
        self.reset_button.pack(side=tk.LEFT, padx=10)

        # 状态栏
        self.status_var = tk.StringVar()
        self.status_var.set("就绪")
        self.statusbar = tk.Label(self.master, textvariable=self.status_var, bd=1, relief=tk.SUNKEN, anchor=tk.W)
        self.statusbar.pack(side=tk.BOTTOM, fill=tk.X)

    def create_enhancement_controls(self, parent):
        """创建增强选项卡的控制."""
        # 对比度
        self.contrast_label = tk.Label(parent, text="对比度:")
        self.contrast_label.grid(row=0, column=0, padx=5, pady=2)
        self.contrast_var = tk.StringVar()  # 创建 StringVar
        self.contrast_var.set(1.0)  # 设置初始值
        self.contrast_var.trace("w", lambda name, index, mode, var=self.contrast_var: self.apply_enhancements("contrast", var.get()))  # 监听值变化
        self.contrast_scale = tk.Scale(parent, from_=0.1, to=3.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.contrast_var, length=200)  # 修改
        self.contrast_scale.grid(row=0, column=1, padx=5, pady=2)

        # 亮度
        self.brightness_label = tk.Label(parent, text="亮度:")
        self.brightness_label.grid(row=1, column=0, padx=5, pady=2)
        self.brightness_var = tk.StringVar()  # 创建 StringVar
        self.brightness_var.set(1.0)  # 设置初始值
        self.brightness_var.trace("w", lambda name, index, mode, var=self.brightness_var: self.apply_enhancements("brightness", var.get()))  # 监听值变化
        self.brightness_scale = tk.Scale(parent, from_=0.1, to=3.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.brightness_var, length=200)  # 修改
        self.brightness_scale.grid(row=1, column=1, padx=5, pady=2)

        # 锐度
        self.sharpness_label = tk.Label(parent, text="锐度:")
        self.sharpness_label.grid(row=2, column=0, padx=5, pady=2)
        self.sharpness_var = tk.StringVar()  # 创建 StringVar
        self.sharpness_var.set(1.0)  # 设置初始值
        self.sharpness_var.trace("w", lambda name, index, mode, var=self.sharpness_var: self.apply_enhancements("sharpness", var.get()))  # 监听值变化
        self.sharpness_scale = tk.Scale(parent, from_=0.1, to=3.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.sharpness_var, length=200)  # 修改
        self.sharpness_scale.grid(row=2, column=1, padx=5, pady=2)

        # 色彩饱和度
        self.color_label = tk.Label(parent, text="饱和度:")
        self.color_label.grid(row=3, column=0, padx=5, pady=2)
        self.color_var = tk.StringVar()  # 创建 StringVar
        self.color_var.set(1.0)  # 设置初始值
        self.color_var.trace("w", lambda name, index, mode, var=self.color_var: self.apply_enhancements("color", var.get()))  # 监听值变化
        self.color_scale = tk.Scale(parent, from_=0.0, to=2.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.color_var, length=200)  # 修改
        self.color_scale.grid(row=3, column=1, padx=5, pady=2)

        # 色调调整
        self.hue_label = tk.Label(parent, text="色调:")
        self.hue_label.grid(row=0, column=2, padx=5, pady=2)
        self.hue_var = tk.StringVar()  # 创建 StringVar
        self.hue_var.set(0)  # 设置初始值
        self.hue_var.trace("w", lambda name, index, mode, var=self.hue_var: self.apply_enhancements("hue", var.get()))  # 监听值变化
        self.hue_scale = tk.Scale(parent, from_=-180, to=180, resolution=1, orient=tk.HORIZONTAL, variable=self.hue_var, length=200)  # 修改
        self.hue_scale.grid(row=0, column=3, padx=5, pady=2)

        # Gamma 校正
        self.gamma_label = tk.Label(parent, text="Gamma:")
        self.gamma_label.grid(row=1, column=2, padx=5, pady=2)
        self.gamma_var = tk.StringVar()  # 创建 StringVar
        self.gamma_var.set(1.0)  # 设置初始值
        self.gamma_var.trace("w", lambda name, index, mode, var=self.gamma_var: self.apply_enhancements("gamma", var.get()))  # 监听值变化
        self.gamma_scale = tk.Scale(parent, from_=0.1, to=5.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.gamma_var, length=200)  # 修改
        self.gamma_scale.grid(row=1, column=3, padx=5, pady=2)

    def create_conversion_controls(self, parent):
        """创建转换选项卡的控制."""
        # 灰度转换按钮
        self.grayscale_button = tk.Button(parent, text="转换为灰度", command=self.convert_to_grayscale)
        self.grayscale_button.grid(row=0, column=0, padx=5, pady=5)

        # 翻转图像
        self.flip_x_button = tk.Button(parent, text="水平翻转", command=self.flip_image_x)
        self.flip_x_button.grid(row=0, column=1, padx=5, pady=5)

        self.flip_y_button = tk.Button(parent, text="垂直翻转", command=self.flip_image_y)
        self.flip_y_button.grid(row=0, column=2, padx=5, pady=5)

        # 旋转图像
        self.rotate_button = tk.Button(parent, text="旋转图像", command=self.rotate_image)
        self.rotate_button.grid(row=1, column=0, padx=5, pady=5)

        # 裁剪图像
        self.crop_button = tk.Button(parent, text="裁剪图像", command=self.crop_image)
        self.crop_button.grid(row=1, column=1, padx=5, pady=5)

    def create_filtering_controls(self, parent):
        """创建滤波选项卡的控制."""
        # 模糊
        self.blur_button = tk.Button(parent, text="模糊", command=self.apply_blur)
        self.blur_button.grid(row=0, column=0, padx=5, pady=5)

        # 边缘检测
        self.edge_enhance_button = tk.Button(parent, text="边缘增强", command=self.apply_edge_enhance)
        self.edge_enhance_button.grid(row=0, column=1, padx=5, pady=5)

        # 浮雕效果
        self.emboss_button = tk.Button(parent, text="浮雕效果", command=self.apply_emboss)
        self.emboss_button.grid(row=0, column=2, padx=5, pady=5)

        # 自定义卷积核
        self.custom_filter_button = tk.Button(parent, text="自定义滤波", command=self.apply_custom_filter)
        self.custom_filter_button.grid(row=1, column=0, padx=5, pady=5)

    def select_image(self):
        filename = filedialog.askopenfilename(initialdir=".", title="选择图像", filetypes=(("图像文件", "*.png;*.jpg;*.jpeg;*.tiff;*.bmp"), ("所有文件", "*.*")))  # 支持更多格式
        if filename:
            try:
                self.original_image = Image.open(filename)
                # 确保图像是 RGB 模式
                if self.original_image.mode != "RGB":
                    self.original_image = self.original_image.convert("RGB")
                self.processed_image = self.original_image.copy()  # 复制一份作为处理后的图像
                self.image_path = filename
                self.display_image(self.original_image)
                self.status_var.set(f"已加载: {filename}")
                self.show_histogram()  # 加载图像后自动显示直方图

                # 初始化所有增强参数
                self.contrast_value = float(self.contrast_var.get())
                self.brightness_value = float(self.brightness_var.get())
                self.sharpness_value = float(self.sharpness_var.get())
                self.color_value = float(self.color_var.get())
                self.hue_value = int(self.hue_var.get())
                self.gamma_value = float(self.gamma_var.get())

            except FileNotFoundError:
                messagebox.showerror("错误", f"文件未找到: {filename}")
                self.status_var.set("文件未找到")
            except UnidentifiedImageError:
                messagebox.showerror("错误", f"无法识别的图像格式: {filename}")
                self.status_var.set("无法识别的图像格式")
            except Exception as e:
                messagebox.showerror("错误", f"打开图像时发生错误: {e}")
                self.status_var.set("错误")

    def select_folder(self):
        """选择文件夹进行批量处理."""
        folder_selected = filedialog.askdirectory()
        if folder_selected:
            try:
                self.process_folder(folder_selected)
            except Exception as e:
                messagebox.showerror("错误", f"批量处理文件夹失败: {e}")
                self.status_var.set("批量处理失败")

    def process_folder(self, folder_path):
        """批量处理文件夹中的图像."""
        image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp'))]
        if not image_files:
            messagebox.showinfo("提示", "文件夹中没有找到可处理的图像文件。")
            return

        # 创建一个新目录来保存处理后的图像
        output_folder = os.path.join(folder_path, "processed_images")
        os.makedirs(output_folder, exist_ok=True)

        for image_file in image_files:
            image_path = os.path.join(folder_path, image_file)
            try:
                img = Image.open(image_path)
                processed_img = self.apply_all_enhancements(img)  # 应用所有增强

                # 构建输出路径，并将处理后的图像保存到新目录
                output_path = os.path.join(output_folder, "processed_" + image_file)
                image_conversion.save_image(processed_img, output_path)

            except FileNotFoundError:
                print(f"警告: 文件未找到: {image_path}")
            except UnidentifiedImageError:
                print(f"警告: 无法识别的图像格式: {image_path}")
            except Exception as e:
                print(f"警告: 处理图像时发生错误: {image_path}, 错误信息: {e}")

        messagebox.showinfo("成功", f"已完成批量处理，处理后的图像保存在: {output_folder}")
        self.status_var.set("批量处理完成")

    def display_image(self, image):
        """显示图像在 GUI 界面上."""
        try:
            # 调整图像大小以适应界面
            resized_image = utils.resize_image_for_display(image, max_width=600, max_height=400)

            self.tk_image = ImageTk.PhotoImage(resized_image)
            self.image_label.config(image=self.tk_image)
            self.image_label.image = self.tk_image  # 保持引用，防止垃圾回收
            self.status_var.set("图像已显示")

        except Exception as e:
            messagebox.showerror("错误", f"无法显示图像: {e}")
            self.status_var.set("错误")

    def apply_enhancements(self, enhancement_type, value):
        """应用增强效果 (统一处理)."""
        if self.original_image:
            try:
                value = float(value)  # 确保 value 是 float
                print(f"apply_enhancements: 开始 - 类型: {enhancement_type}, 值: {value}")  # 调试信息

                # 设置增强值
                if enhancement_type == "contrast":
                    self.contrast_value = value
                elif enhancement_type == "brightness":
                    self.brightness_value = value
                elif enhancement_type == "sharpness":
                    self.sharpness_value = value
                elif enhancement_type == "color":
                    self.color_value = value
                elif enhancement_type == "hue":
                    self.hue_value = int(value)
                elif enhancement_type == "gamma":
                    self.gamma_value = value
                else:
                    raise ValueError(f"未知的增强类型: {enhancement_type}")

                # 应用所有增强效果
                self.processed_image = self.apply_all_enhancements(self.original_image)

                # 更新图像显示和直方图
                self.display_image(self.processed_image)
                self.show_histogram()

                print(f"apply_enhancements: 结束 - {enhancement_type} 应用完成")  # 调试信息

            except ValueError as ve:
                messagebox.showerror("错误", f"值错误: {ve}")  # 更具体的错误信息
                self.status_var.set("值错误")
            except Exception as e:
                messagebox.showerror("错误", f"调整 {enhancement_type} 失败: {e}")
                self.status_var.set("错误")

    def apply_all_enhancements(self, image):
        """应用所有增强效果."""
        try:
            print("apply_all_enhancements: 开始 - 应用所有增强效果")  # 调试信息
            # 复制一份图像，以免修改原始图像
            img = image.copy()

            # 应用所有增强效果
            print(f"adjust_contrast: 应用 - 值: {self.contrast_value}")
            img = image_enhancement.adjust_contrast(img, self.contrast_value)
            print("adjust_contrast: 完成")

            print(f"adjust_brightness: 应用 - 值: {self.brightness_value}")
            img = image_enhancement.adjust_brightness(img, self.brightness_value)
            print("adjust_brightness: 完成")

            print(f"sharpen_image: 应用 - 值: {self.sharpness_value}")
            img = image_enhancement.sharpen_image(img, self.sharpness_value)
            print("sharpen_image: 完成")

            print(f"adjust_color: 应用 - 值: {self.color_value}")
            img = image_enhancement.adjust_color(img, self.color_value)
            print("adjust_color: 完成")

            print(f"adjust_hue: 应用 - 值: {self.hue_value}")
            img = image_enhancement.adjust_hue(img, self.hue_value)
            print("adjust_hue: 完成")

            print(f"adjust_gamma: 应用 - 值: {self.gamma_value}")
            img = image_enhancement.adjust_gamma(img, self.gamma_value)
            print("adjust_gamma: 完成")

            print("apply_all_enhancements: 结束 - 所有增强效果应用完成")  # 调试信息
            return img
        except Exception as e:
            messagebox.showerror("错误", f"应用增强效果失败: {e}")
            self.status_var.set("应用增强效果失败")
            return image  # 如果出错，返回原始图像

    def add_watermark(self):
        """添加水印功能."""
        if self.original_image:
            try:
                text = simpledialog.askstring("添加水印", "请输入水印文本:")
                if text:
                    self.processed_image = image_conversion.add_text_watermark(self.original_image, text)
                    self.display_image(self.processed_image)
                    self.status_var.set("水印已添加")
                    self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"添加水印失败: {e}")
                self.status_var.set("添加水印失败")

    def convert_to_grayscale(self):
        """转换为灰度图像."""
        if self.original_image:
            try:
                self.processed_image = image_conversion.convert_to_grayscale(self.original_image)
                self.display_image(self.processed_image)
                self.status_var.set("已转换为灰度图像")
                self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"转换为灰度失败: {e}")
                self.status_var.set("错误")

    def flip_image_x(self):
        """水平翻转图像."""
        if self.original_image:
            try:
                self.processed_image = image_conversion.flip_image(self.original_image, method="horizontal")
                self.display_image(self.processed_image)
                self.status_var.set("水平翻转已完成")
                self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"水平翻转失败: {e}")
                self.status_var.set("错误")

    def flip_image_y(self):
        """垂直翻转图像."""
        if self.original_image:
            try:
                self.processed_image = image_conversion.flip_image(self.original_image, method="vertical")
                self.display_image(self.processed_image)
                self.status_var.set("垂直翻转已完成")
                self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"垂直翻转失败: {e}")
                self.status_var.set("错误")

    def rotate_image(self):
        """旋转图像."""
        if self.original_image:
            try:
                angle = simpledialog.askinteger("旋转图像", "请输入旋转角度 (0-360):", minvalue=0, maxvalue=360)
                if angle is not None:
                    self.processed_image = image_conversion.rotate_image(self.original_image, angle)
                    self.display_image(self.processed_image)
                    self.status_var.set(f"图像旋转了 {angle} 度")
                    self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"旋转图像失败: {e}")
                self.status_var.set("错误")

    def crop_image(self):
        """裁剪图像."""
        if self.original_image:
            try:
                # 这里可以实现一个更复杂的裁剪界面, 例如使用鼠标拖动来选择裁剪区域
                # 为了简化, 这里直接使用对话框输入裁剪参数
                width = self.original_image.size[0]
                height = self.original_image.size[1]
                x1 = simpledialog.askinteger("裁剪图像", "请输入左上角 X 坐标:", minvalue=0, maxvalue=width)
                y1 = simpledialog.askinteger("裁剪图像", "请输入左上角 Y 坐标:", minvalue=0, maxvalue=height)
                x2 = simpledialog.askinteger("裁剪图像", "请输入右下角 X 坐标:", minvalue=x1, maxvalue=width)
                y2 = simpledialog.askinteger("裁剪图像", "请输入右下角 Y 坐标:", minvalue=y1, maxvalue=height)

                if x1 is not None and y1 is not None and x2 is not None and y2 is not None:
                    self.processed_image = image_conversion.crop_image(self.original_image, (x1, y1, x2, y2))
                    self.display_image(self.processed_image)
                    self.status_var.set("图像已裁剪")
                    self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"裁剪图像失败: {e}")
                self.status_var.set("错误")

    def apply_blur(self):
        """应用模糊效果."""
        if self.original_image:
            try:
                self.processed_image = image_filtering.apply_blur(self.original_image)
                self.display_image(self.processed_image)
                self.status_var.set("模糊效果已应用")
                self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"应用模糊效果失败: {e}")
                self.status_var.set("错误")

    def apply_edge_enhance(self):
        """应用边缘增强效果."""
        if self.original_image:
            try:
                self.processed_image = image_filtering.apply_edge_enhance(self.original_image)
                self.display_image(self.processed_image)
                self.status_var.set("边缘增强效果已应用")
                self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"应用边缘增强效果失败: {e}")
                self.status_var.set("错误")

    def apply_emboss(self):
        """应用浮雕效果."""
        if self.original_image:
            try:
                self.processed_image = image_filtering.apply_emboss(self.original_image)
                self.display_image(self.processed_image)
                self.status_var.set("浮雕效果已应用")
                self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"应用浮雕效果失败: {e}")
                self.status_var.set("错误")

    def apply_custom_filter(self):
        """应用自定义卷积核滤波."""
        if self.original_image:
            try:
                # 这里可以弹出一个对话框, 让用户输入自定义的卷积核
                # 为了简化, 这里直接使用一个预定义的卷积核
                kernel = (
                    -1, -1, -1,
                    -1, 9, -1,
                    -1, -1, -1
                )
                self.processed_image = image_filtering.apply_custom_filter(self.original_image, kernel)
                self.display_image(self.processed_image)
                self.status_var.set("自定义滤波已应用")
                self.show_histogram()
            except Exception as e:
                messagebox.showerror("错误", f"应用自定义滤波失败: {e}")
                self.status_var.set("错误")

    def save_image(self):
        """保存图像."""
        if self.processed_image:
            try:
                filename = filedialog.asksaveasfilename(defaultextension=".png", filetypes=(("PNG 文件", "*.png"), ("JPEG 文件", "*.jpg;*.jpeg"), ("TIFF 文件", "*.tiff"), ("BMP 文件", "*.bmp"),("所有文件", "*.*")))  # 支持更多格式
                if filename:
                    image_conversion.save_image(self.processed_image, filename)
                    messagebox.showinfo("成功", "图像已保存")
                    self.status_var.set(f"图像已保存到 {filename}")
            except ValueError as ve:
                messagebox.showerror("错误", f"保存图像时发生值错误: {ve}")
                self.status_var.set("值错误")
            except OSError as oe:
                messagebox.showerror("错误", f"保存图像时发生操作系统错误: {oe}")
                self.status_var.set("操作系统错误")
            except Exception as e:
                messagebox.showerror("错误", f"保存图像失败: {e}")
                self.status_var.set("错误")

    def show_histogram(self):
        """显示图像直方图."""
        if self.processed_image:
            try:
                # 计算直方图
                histogram = self.processed_image.histogram()

                # 绘制直方图
                self.histogram_ax.clear()  # 清除之前的图像
                if self.processed_image.mode == 'L':  # 灰度图像
                    self.histogram_ax.plot(histogram)
                else:  # 彩色图像
                    r_histogram = histogram[:256]
                    g_histogram = histogram[256:512]
                    b_histogram = histogram[512:]
                    self.histogram_ax.plot(r_histogram, color='red', label='Red')
                    self.histogram_ax.plot(g_histogram, color='green', label='Green')
                    self.histogram_ax.plot(b_histogram, color='blue', label='Blue')
                    self.histogram_ax.legend()  # 显示图例

                self.histogram_ax.set_title('图像直方图')
                self.histogram_ax.set_xlabel('像素值')
                self.histogram_ax.set_ylabel('像素数')

                self.canvas.draw()  # 重新绘制画布

                # 更新状态栏
                self.status_var.set("直方图已显示")
                self.histogram_label.pack_forget()  # 隐藏提示信息

            except Exception as e:
                messagebox.showerror("错误", f"显示直方图失败: {e}")
                self.status_var.set("错误")
                self.histogram_label.config(text="无法显示直方图")  # 显示错误提示信息
                self.histogram_label.pack()

    def reset_image(self):
        """重置图像到原始状态."""
        if self.original_image:
            try:
                self.processed_image = self.original_image.copy()
                self.display_image(self.processed_image)
                self.status_var.set("图像已重置")
                self.show_histogram()

                # 重置所有增强参数到初始值
                self.contrast_var.set(1.0)
                self.brightness_var.set(1.0)
                self.sharpness_var.set(1.0)
                self.color_var.set(1.0)
                self.hue_var.set(0)
                self.gamma_var.set(1.0)
            except Exception as e:
                messagebox.showerror("错误", f"重置图像失败: {e}")
                self.status_var.set("错误")

if __name__ == "__main__":
    root = tk.Tk()
    gui = ImageProcessorGUI(root)
    root.mainloop()